#include "Stack.h"
#include "Sort.h"

// 栈的初始化

void SInit (ST* ps)
{

    assert (ps) ;

    ps -> arr = NULL ;

    ps -> top = ps -> capacity = 0 ;

}

// 栈的销毁

void SDestory (ST* ps)
{

    assert (ps) ;

    if (ps -> arr)
    {

        free (ps -> arr) ;

    }
    
    ps -> arr = NULL ;

    ps -> top = ps -> capacity = 0 ;

}

// 入栈

void SPush (ST* ps , StackDataType x)
{

    assert (ps) ;

    if (ps -> top == ps -> capacity)
    {

        int newcapacity = ps -> capacity == 0 ? 4 : 2 * ps -> capacity ;

        StackDataType* tmp = (StackDataType*) realloc (ps -> arr , sizeof (StackDataType) * newcapacity) ;

        if (tmp == NULL)
        {

            perror ("realloc fail!") ;

            exit (1) ;

        }

        ps -> arr = tmp ;

        ps -> capacity = newcapacity ;

    }

    ps -> arr [ps -> top] = x ;

    (ps -> top)++ ;

}

// 出栈

void SPop (ST* ps)
{

    assert (!SEmpty (ps)) ;

    (ps -> top)-- ;

}

// 判断栈是否为空

bool SEmpty (ST* ps)
{

    assert (ps) ;

    return ps -> top == 0 ;

}

// 取栈顶元素

StackDataType STop (ST* ps)
{

    assert (!SEmpty (ps)) ;

    return ps -> arr [ps -> top - 1] ; // 返回元素即可,不需要删除

}